from lib.net.index import wlan
from lib.sensors.ssd1306.oled import OLED
from lib.config.index import sensor_config
from lib import api
from utils import common, format
import sys

__service__ = "loop_actions"
__description__ = "http actions loop"

def handle_response(resp, key=""):
    if not key:
        return resp
    if not key in resp:
        print("no actions now")
        return None
    else:
        return resp[key]


def handle_poem(resp):
    """处理诗词显示
    """
    resp = format.format_network_response(resp)
    actions = handle_response(resp, "actions")
    # print(resp, actions)
    if not actions or len(actions) == 0:
        return

    content = actions[0]["action"]["data"]["content"]
    print("get poem content:", content)

    # 获取点
    fonts = api.ssd1306.get_ssd1306_fonts(content.encode("utf-8"))
    # print(fonts)
    font12 = fonts["font12"]

    oled_config = sensor_config.get_sensor("ssd1306")
    scl = oled_config["scl"]
    sda = oled_config["sda"]
    width = oled_config["width"]
    height = oled_config["height"]
    _oled = OLED(scl, sda, width, height)
    _oled.font_renderer.set_font(font12, 12)
    _oled.font_renderer.reset_line()
    _oled.font_renderer.show_text(content)


def handle_tts(resp, play):
    """处理语音

    Args:
        resp (_type_): _description_
    """
    resp = format.format_network_response(resp)
    actions = handle_response(resp, "actions")

    if not actions or len(actions) == 0:
        return None

    content = actions[0]["action"]["data"]["content"]

    if play:
        handle_tts_play(content)
        return content

    handle_tts_audio(content)

    # 显示播放提示
    try:
        content = "播放语音:\n" + content
        response = api.ssd1306.get_ssd1306_fonts(content.encode("utf-8"))
        # print(response)
        json_resp = format.format_network_response(response)
        font12 = json_resp["font12"]
    #       ops.init_oled()
    #       ops.set_font(font12, 12)
    #       ops.reset_line()
    #       ops.show_text(content)
    except Exception as e:
        sys.print_exception(e)


def handle_tts_audio(content):
    print("input tts content:", content)
    # 获取音频文件内容,写入到文件
    audio_base64 = api.tts.get_tts_audio(content)
    return audio_base64


is_playing = False


def handle_tts_play(content):
    global is_playing

    # 如果正在播放，跳过这次请求
    if is_playing:
        return
    from lib.config.index import sensor_config
    from lib.sensors.max98357 import Max98357

    is_playing = True
    common.print_gc_info()
    # print(content)
    response = api.tts.get_tts_audio_raw(content)
    # print(response)
    try:
        max98357_config = sensor_config.get_sensor("MAX98357")
        sck = max98357_config["sck"]
        ws = max98357_config["ws"]
        sd = max98357_config["sd"]
        max98357 = Max98357(sck, ws, sd)

        while True:
            read_data = response.raw.read(1024 * 8)
            if not read_data:
                break
            max98357.play_bytes(read_data)
    except Exception as e:
        print(e)
        is_playing = False
    response.close()
    is_playing = False

def init():
    # 检查当前网络状态和网络模式
    if not wlan.is_connected():
        print("wifi not connected")

async def run():
    pass
